const weiUser = require('wei-user');
const {
  preBind,
  postBind
} = weiUser.lib.utils.relate;
const {
  LOG_TYPE
} = weiUser.common.constants;
const {
  decryptAlipayData,
} = weiUser.lib.utils.weixin;
const { initWeixin } = weiUser.lib.thirdParty;
const { ERROR } = weiUser.common.error;

/**
 * 通过微信绑定手机号
 * @tutorial https://uniapp.dcloud.net.cn/uniCloud/uni-id-pages.html#bind-mobile-by-mp-weixin
 * @param {Object} params
 * @param {String} params.encryptedData   微信获取手机号返回的加密信息
 * @returns
 */
module.exports = async function (params = {}) {
  /**
   * 微信小程序的规则是客户端应先使用checkSession接口检测上次获取的sessionKey是否仍有效
   * 如果有效则直接使用上次存储的sessionKey即可
   * 如果无效应重新调用login接口再次刷新sessionKey
   * 因此此接口不应直接使用客户端login获取的code，只能使用缓存的sessionKey
   */
  const schema = {
    encryptedData: {
      required: false,
      type: 'string'
    },
  }
  const {
    encryptedData,
  } = params
  this.middleware.validate(params, schema)

  if (!encryptedData) {
    return {
      errCode: ERROR.INVALID_PARAM
    }
  }

  const uid = this.authInfo.uid
	
	//直接从密文中获取手机信息
	const { code, mobile } = decryptAlipayData.call(this, { encryptedData });
	
	if (code !== '10000') {
		await this.middleware.uniIdLog({
		  success: false,
		  type: LOG_TYPE.LOGIN
		})
		throw {
		  errCode: ERROR.GET_THIRD_PARTY_ACCOUNT_FAILED
		}
	}

  const bindAccount = {
    mobile
  }
  await preBind.call(this, {
    uid,
    bindAccount,
    logType: LOG_TYPE.BIND_MOBILE
  })
  await postBind.call(this, {
    uid,
    bindAccount,
    extraData: {
      mobile_confirmed: 1
    },
    logType: LOG_TYPE.BIND_MOBILE
  })
  return {
    errCode: 0
  }
}
